package com.huluobo.a2206koltindouyin.live

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.animation.Animation.AnimationListener
import android.widget.ImageView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2206koltindouyin.R
import com.huluobo.a2206koltindouyin.adapter.GiftAdapter
import com.huluobo.a2206koltindouyin.adapter.MessageAdapter
import com.huluobo.a2206koltindouyin.databinding.ActivityLiveBinding
import com.huluobo.a2206koltindouyin.shop.ShopActivity
import com.huluobo.a2206koltindouyin.utils.ImageUtils
import com.huluobo.base.bean.GiftBean
import com.huluobo.base.bean.MessageEntity
import com.huluobo.base.bean.Money
import com.huluobo.base.bean.VideoBean
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import top.littlefogcat.danmakulib.danmaku.Danmaku
import top.littlefogcat.danmakulib.danmaku.DanmakuManager

@AndroidEntryPoint
class LiveActivity : BaseActivity<ActivityLiveBinding, LiveViewModel>() {
    private lateinit var videoBean: VideoBean
    private lateinit var giftAdapter: GiftAdapter
    private lateinit var giftBean: GiftBean
    private lateinit var money: Money
    private lateinit var messageAdapter: MessageAdapter
    override fun initData() {
        vm.followAuthSuccess.observe(this) {
            ToastUtils.showLong(it)
            binding.liveFollowBtn.text = "已关注"
            binding.liveFollowBtn.setBackgroundResource(R.drawable.shape_alpha_black)
            videoBean.guanzhu = 1
        }

        vm.cancelFollowSuccess.observe(this) {
            ToastUtils.showLong(it)
            binding.liveFollowBtn.text = "关注"
            binding.liveFollowBtn.setBackgroundResource(R.drawable.shape_red)
            videoBean.guanzhu = 0
        }
        vm.getGiftSuccess.observe(this) {
            giftAdapter.data.clear()
            giftAdapter.data.addAll(it)
            giftAdapter.notifyDataSetChanged()
        }

        vm.queryUserMoneySuccess.observe(this) {
            money = it
            binding.liveUserMontyTv.text = "余额:${money.money}抖币"
        }

        vm.updateUserMoneySuccess.observe(this) {
            Log.i("TagA", "更新余额:$it")
        }
    }

    override fun initView() {
        videoBean = intent.getSerializableExtra(Const.PARAM_VIDEO_BEAN) as VideoBean
        binding.livePlayer.backButton.visibility = View.GONE
        binding.livePlayer.setUp(videoBean.videopath, true, "")

        ImageUtils.loadCircleImage(this, videoBean.headpath, binding.liveUserIconIv)
        binding.liveUsernameTv.text = videoBean.authname

        binding.liveFollowBtn.text = if (videoBean.guanzhu == 0) "关注" else "已关注"
        binding.liveFollowBtn.setBackgroundResource(if (videoBean.guanzhu == 0) R.drawable.shape_red else R.drawable.shape_alpha_black)
        binding.liveLikeCountTv.text = "${videoBean.like_count}人喜欢"

        binding.liveFollowBtn.setOnClickListener {
            if (videoBean.guanzhu == 0) {
                val map = mutableMapOf<String, String>()
                map[Const.PARAM_AUTHNAME] = videoBean.authname
                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_PARSE.toMediaTypeOrNull(), json)
                vm.followAuth(body)
            } else {
                val map = mutableMapOf<String, String>()
                map[Const.PARAM_AUTHNAME] = videoBean.authname
                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_PARSE.toMediaTypeOrNull(), json)
                vm.cancelFollow(body)
            }
        }

        binding.liveLikeView.addLikeImages(
            R.drawable.fav_0,
            R.drawable.fav_1,
            R.drawable.fav_2,
            R.drawable.fav_3,
            R.drawable.fav_4,
            R.drawable.fav_5
        )

        binding.liveLikeIv.setOnClickListener {
            binding.liveLikeView.addFavor()
        }

        binding.liveDanmuIv.setOnClickListener {
            binding.liveDanmuLayoutLl.visibility = View.VISIBLE
        }

        binding.liveDanmuSendIv.setOnClickListener {
            val danmuString = binding.liveDanmuEt.text.toString()
            if (!danmuString.isNullOrEmpty()) {
                val danmaku = Danmaku()
                danmaku.text = danmuString
                danmaku.size = 30
                DanmakuManager.getInstance().init(this, binding.liveDanmuView)
                DanmakuManager.getInstance().send(danmaku)

                binding.liveDanmuEt.text.clear()
                binding.liveDanmuLayoutLl.visibility = View.GONE

            } else {
                ToastUtils.showLong("弹幕内容不能为空")
            }
        }

        binding.liveGiftRv.layoutManager = GridLayoutManager(this, 5)
        giftAdapter = GiftAdapter()
        binding.liveGiftRv.adapter = giftAdapter

        binding.liveGiftIv.setOnClickListener {
            binding.liveGiftLayoutCl.visibility = View.VISIBLE
            vm.getGift()
            vm.queryUserMoney(SPUtils.getInstance().getString(Const.PARAM_USERNAME))
        }

        binding.liveCloseTv.setOnClickListener {
            binding.liveGiftLayoutCl.visibility = View.GONE
        }

        giftAdapter.setOnItemClickListener { adapter, view, position ->
            giftBean = giftAdapter.data[position]
            binding.liveGiftSelectTv.text = giftBean.giftname
            ImageUtils.loadImage(this, giftBean.giftpath, binding.liveGiftSelectIv)
        }

        binding.liveGiftSendBtn.setOnClickListener {
            sendGift()
        }

        binding.liveInputTv.setOnClickListener {
            binding.liveChatRoomLayoutLl.visibility = View.VISIBLE
        }

        binding.liveChatRoomRv.layoutManager = LinearLayoutManager(this)
        messageAdapter = MessageAdapter()
        binding.liveChatRoomRv.adapter = messageAdapter

        binding.liveCharRoomSendIv.setOnClickListener {
            if (binding.liveCharRoomEt.text.toString().isNotEmpty()) {
                val messageEntity = MessageEntity(
                    SPUtils.getInstance().getString(Const.PARAM_USERNAME),
                    binding.liveCharRoomEt.text.toString()
                )
                messageAdapter.data.add(messageEntity)
                messageAdapter.notifyDataSetChanged()
                binding.liveChatRoomRv.scrollToPosition(messageAdapter.data.size - 1)
                binding.liveCharRoomEt.text.clear()
                binding.liveChatRoomLayoutLl.visibility = View.GONE
            } else {
                ToastUtils.showLong("请输入聊天内容")
            }
        }

        binding.liveCartIv.setOnClickListener {
            val intent = Intent(this, ShopActivity::class.java)
            startActivity(intent)
        }

    }

    private fun sendGift() {
        if (money.money < giftBean.price) {
            ToastUtils.showLong("用户余额不足,请充值")
            return
        }

        val newMoney = money.money - giftBean.price
        binding.liveUserMontyTv.text = "余额:${newMoney}抖币"

        //将查询到的用户余额的对象中的money,把产生扣款后的money,给他赋值
        money.money = newMoney
        vm.updateUserMoney(money)

        val giftAnimView = ImageView(this)
        val params = ConstraintLayout.LayoutParams(200, 200)
        giftAnimView.layoutParams = params

        binding.liveRootCl.addView(giftAnimView)
        ImageUtils.loadImage(this, giftBean.giftpath, giftAnimView)

        val screenWidth = binding.liveRootCl.measuredWidth
        val screenHeight = binding.liveRootCl.measuredHeight

        val offset = 100
        val translationY =
            ObjectAnimator.ofFloat(
                giftAnimView,
                "translationY",
                (screenHeight - offset).toFloat(),
                (screenHeight / 2 - offset).toFloat(),
                (screenHeight / 3 - offset).toFloat(),
                (screenHeight / 2 - offset).toFloat(),
                (screenHeight / 3 * 2 - offset).toFloat()
            )

        val translationX =
            ObjectAnimator.ofFloat(
                giftAnimView,
                "translationX",
                (screenWidth / 2 - offset).toFloat(),
                (screenWidth / 4 - offset).toFloat(),
                (screenWidth / 2 - offset).toFloat(),
                (screenWidth / 4 * 3 - offset).toFloat(),
                (screenWidth / 2 - offset).toFloat()
            )

        val rotation = ObjectAnimator.ofFloat(giftAnimView, "rotation", 0f, 1800f)
        val scaleX = ObjectAnimator.ofFloat(giftAnimView, "scaleX", 1f, 2f, 1f, 3f, 1f, 2f, 1f)
        val scaleY = ObjectAnimator.ofFloat(giftAnimView, "scaleY", 1f, 2f, 1f, 3f, 1f, 2f, 1f)
        val alpha = ObjectAnimator.ofFloat(giftAnimView, "alpha", 1f, 0f)

        val animatorSet = AnimatorSet()
        animatorSet.duration = 3000
        animatorSet.playTogether(translationX, translationY, rotation, scaleX, scaleY, alpha)
        animatorSet.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationStart(animation: Animator) {
                super.onAnimationStart(animation)
                binding.liveGiftLayoutCl.visibility = View.GONE
            }

            override fun onAnimationEnd(animation: Animator) {
                super.onAnimationEnd(animation)
                binding.liveRootCl.removeView(giftAnimView)
            }
        })
        animatorSet.start()
    }
}